<template>
  <div>
    <el-card :body-style="{ padding: 0 }" :bordered="false" class="ivu-mt" shadow="never">
      <div class="padding-add">
        <el-form
          ref="tableFrom"
          :label-position="labelPosition"
          :label-width="labelWidth"
          :model="tableFrom"
          inline
          @submit.native.prevent
        >
          <el-form-item label="代理信息：" label-for="leader_content">
            <el-input
              v-model="tableFrom.leader_content"
              class="form_content_width"
              placeholder="请输入代理电话、代理代理码、代理名称"
            />
          </el-form-item>
          <el-form-item label="用户信息：" label-for="user_content">
            <el-input
              v-model="tableFrom.user_content"
              class="form_content_width"
              placeholder="请输入用户电话、用户代理码、用户名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button v-db-click type="primary" @click="userSearchs">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card :bordered="false" class="ivu-mt mt16" shadow="never">
      <div class="operation-buttons">
        <el-button v-auth="['admin-marketing-store_coupon-add']" v-db-click icon="md-add" type="primary" @click="add">
          录入订单
        </el-button>
        <el-button v-db-click type="success" @click="handleBatchAction" :disabled="ids.length === 0">
          批量处理
        </el-button>
        <el-button v-db-click type="primary" plain @click="handleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </el-button>
      </div>
      <div v-if="ids.length" class="selection-alert">
        <el-alert show-icon type="info" :closable="false">
          <template slot="title">
            已选择<i class="selection-count"> {{ ids.length }} </i>项
          </template>
        </el-alert>
      </div>
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableList"
        class="mt14"
        highlight-current-row
        no-filtered-userFrom-text="暂无筛选结果"
        no-userFrom-text="暂无数据"
      >
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.isChecked"
              @change="(val) => handleCheckboxChange(val, scope.row)"
              :disabled="scope.row.paid === 1"
            ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="ID" width="40">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单id" min-width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.order_id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员名称" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员手机号" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员地址" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.area }}{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" width="250">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.store_name + ' * ' + scope.row.num" placement="top">
              <div
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  max-width: 300px;
                  text-overflow: ellipsis;
                  overflow: hidden;
                  white-space: nowrap;
                "
              >
                <img v-lazy="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px" />
                <span>{{ scope.row.store_name }}</span>
                <span> * {{ scope.row.num }}</span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="总金额" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.total_price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公司收益" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.company_price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" min-width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.add_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="代理名称" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.leader_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="代理电话" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.leader_phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" min-width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.paid === 1 ? 'success' : 'danger'">
              {{ scope.row.paid === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <a v-db-click @click="payOrder(scope.row.id)" v-if="scope.row.paid !== 1">支付订单</a>
            <span v-else class="disabled-action">已支付</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :limit.sync="tableFrom.limit"
          :page.sync="tableFrom.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { releasedissueLogApi } from '@/api/marketing';
import { formatDate } from '@/utils/validate';
import { newOrderListApi, payOrderApi } from '@api/order';

export default {
  name: 'marketing_storeCouponIssue',
  filters: {
    formatDate(time) {
      if (time !== 0) {
        let date = new Date(time * 1000);
        return formatDate(date, 'yyyy-MM-dd hh:mm');
      }
    },
  },
  data() {
    return {
      modals2: false,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,

      tableFrom: {
        leader_content: '',
        user_content: '',
        page: 1,
        limit: 20,
      },
      tableList: [],
      total: 0,
      ids: [], // 选中项的id数组
      isAllSelected: false, // 是否全选
    };
  },
  activated() {
    this.getList();
  },
  computed: {
    ...mapState('media', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : '90px';
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'right';
    },
    // 可选择的订单数量（未支付的订单）
    selectableOrders() {
      return this.tableList.filter((item) => item.paid !== 1);
    },
  },
  methods: {
    // 全选/取消全选
    handleSelectAll() {
      if (this.isAllSelected) {
        // 如果当前是全选状态，则取消全选
        this.tableList.forEach((item) => {
          item.isChecked = false;
        });
        this.ids = [];
        this.isAllSelected = false;
      } else {
        // 如果当前不是全选状态，则全选（只选择未支付的订单）
        this.ids = [];
        this.tableList.forEach((item) => {
          if (item.paid !== 1) {
            item.isChecked = true;
            if (!this.ids.includes(item.id)) {
              this.ids.push(item.id);
            }
          }
        });
        this.isAllSelected = this.ids.length > 0;
      }
    },

    // 处理复选框选择
    handleCheckboxChange(val, row) {
      if (row.paid === 1) {
        return; // 已支付订单不允许选择
      }

      if (val) {
        // 如果选中，添加到ids数组
        if (!this.ids.includes(row.id)) {
          this.ids.push(row.id);
        }
      } else {
        // 如果取消选中，从ids数组中移除
        const index = this.ids.indexOf(row.id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
      }

      // 更新全选状态
      this.isAllSelected = this.selectableOrders.length > 0 && this.ids.length === this.selectableOrders.length;
    },

    // 批量处理
    handleBatchAction() {
      if (this.ids.length === 0) {
        this.$message.warning('请选择要操作的订单');
        return;
      }
      let that = this;
      this.$msgbox({
        title: '批量操作',
        message: `确认对已选择的 ${this.ids.length} 个订单进行批量支付操作吗？`,
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
      })
        .then(() => {
          // 调用批量支付接口
          // const promises = this.ids.map(id => {
          //   return payOrderApi({
          //     id
          //   });
          // });
          payOrderApi({
            // this.ids.join(','),’
            id: that.ids.join(','),
          })
            .then(async (res) => {
              that.$message.success(res.msg);
              that.ids = [];
              that.getList();
            })
            .catch((res) => {
              that.$message.error(res.msg);
            });

        })
        .catch(() => {
          // 取消操作
        });
    },

    getReceivelist(row) {
      this.loading2 = true;
      releasedissueLogApi(row.id, this.receiveFrom)
        .then(async (res) => {
          let data = res.data;
          this.receiveList = data.list;
          this.total2 = res.data.count;
          this.loading2 = false;
        })
        .catch((res) => {
          this.loading2 = false;
          this.$message.error(res.msg);
        });
    },

    // 列表
    getList() {
      this.loading = true;
      newOrderListApi(this.tableFrom)
        .then(async (res) => {
          let data = res.data;
          // 为每行数据添加isChecked属性，用于复选框绑定
          this.tableList = data.list.map((item) => {
            return {
              ...item,
              isChecked: this.ids.includes(item.id) && item.paid !== 1,
            };
          });
          this.total = res.data.count;
          this.loading = false;

          // 更新全选状态
          this.isAllSelected = this.selectableOrders.length > 0 && this.ids.length === this.selectableOrders.length;
        })
        .catch((res) => {
          this.loading = false;
          this.$message.error(res.msg);
        });
    },
    // 表格搜索
    userSearchs() {
      this.tableFrom.page = 1;
      this.getList();
    },
    // 添加
    add() {
      this.$router.push({ path: this.$routeProStr + '/order/create' });
    },
    payOrder(id) {
      let that = this;
      this.$msgbox({
        title: '支付订单',
        message: '确认是否支付订单',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        iconClass: 'el-icon-warning',
        confirmButtonClass: 'btn-custom-cancel',
      })
        .then(() => {
          console.log(id);
          payOrderApi({
            id,
          })
            .then(async (res) => {
              that.$message.success(res.msg);
              that.getList();
            })
            .catch((res) => {
              that.$message.error(res.msg);
            });
        })
        .catch(() => {
          console.log(2);
        });
    },
  },
};
</script>

<style lang="stylus" scoped>
.fa {
  color: #0a6aa1;
  display: block;
}

.sheng {
  color: #ff0000;
  display: block;
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

.operation-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.selection-alert {
  margin-bottom: 15px;
}

.selection-count {
  color: #409EFF;
  font-style: normal;
  margin: 0 3px;
}

.disabled-action {
  color: #999;
  cursor: not-allowed;
}
</style>
